import { parseHTML } from "./parse"

function genProps(attrs) {
    let str = ''
    for (let i = 0; i < attrs.length; i++) {
        let attr = attrs[i]
        if (attr.name === 'style') {
            let obj = {}
            attr.value.split(';').forEach(item => {
                let [key, value] = item.split(':')
                obj[key] = value
            });
            attr.value = obj
        }
        str += `${attr.name}:${JSON.stringify(attr.value)},`

    }
    return `{${str.slice(0, -1)}}`
}

const defaultTagRE = /\{\{((?:.|\r?\n)+?)\}\}/g//{{}}
function gen(node) {
    // debugger
    if (node.type == 1) {
        return codegen(node)
    } else {
        let text = node.text
        if (!defaultTagRE.test(text)) {
            return `_v(${JSON.stringify(text)})`
        } else {// _c 创建元素 _v文本 _s JSON.stringify()
            // console.log(text)
            let tokens = []
            let match
            defaultTagRE.lastIndex = 0// exec 重置
            let lastIndex = 0
            while (match = defaultTagRE.exec(text)) {
                // console.log('match----------',match)
                let index = match.index// 匹配的位置
                if (index > lastIndex) {
                    tokens.push(JSON.stringify(text.slice(lastIndex, index)))
                }
                // console.log(index)
                tokens.push(`_s(${match[1].trim()})`)
                lastIndex = index + match[0].length
            }
            if (lastIndex < text.length) {
                tokens.push(JSON.stringify(text.slice(
                    lastIndex
                )))
            }
            return `_v(${tokens.join('+')})`

        }

        return 'xxx'
    }
}

function genChildren(children) {
    // debugger
    return children.map(child => gen(child)).join(',')
}

function codegen(ast) {
    let children = genChildren(ast.children)
    // debugger
    let code = (
        `_c('${ast.tag}',${ast.attrs.length > 0 ? genProps(ast.attrs) : 'null'}${ast.children.length ? `,${children}` : ''})`)
    return code
}

//VUE3不是正则
export function compileToFunction(template) {
    // 1.将模板转成抽象语法树
    let ast = parseHTML(template)

    // 2.生成render方法，render方法执行后的返回结果为虚拟dom
    let code=codegen(ast)
    code=`with(this){return ${code}}`;
   
    let render=new Function(code)
    //  console.log(render)
    return render
}
